﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using GameEditor.Common.Controls;
using TaskSystemClient.SPM;
using GameEditor.Common;


namespace TaskSystemClient
{
    public partial class ConfigureMileStoneDialog : Form
    {
        public ConfigureMileStoneDialog()
        {
            InitializeComponent();
            InitializeTreeView();
        }
        private List<MileStoneEditData> editDatas = new List<MileStoneEditData>();
        protected void InitializeTreeView()
        {
            tvMileStone.ItemDrag += new TreeListViewDragEvent(tvMileStone_ItemDrag);
            tvMileStone.ItemDrop += new TreeListViewDropEvent(tvMileStone_ItemDrop);
            tvMileStone.ColumnsOptions.ColumnSortEnabled = false;
            
            TreeListColumn column;
            tvMileStone.Columns.Add(new TreeListColumn("编码", "编码", 140)
                {
                    Tag = new MileStoneCodeItemDelegate()
                });
            tvMileStone.Columns.Add(new TreeListColumn("名字", "名字", 240)
                {
                    Tag = new MileStoneNameItemDelegate()
                });
            tvMileStone.Columns.Add(new TreeListColumn("开始时间", "开始时间", 100)
                {
                    Tag = new MileStoneStartTimeItemDelegate()
                });
            tvMileStone.Columns.Add(new TreeListColumn("结束时间", "结束时间", 100)
                {
                    Tag = new MileStoneEndTimeItemDelegate()
                });
            tvMileStone.Columns.Add(new TreeListColumn("负责人", "负责人", 60) 
                {
                    Tag = new MileStoneManagerItemDelegate() 
                });
            tvMileStone.Columns.Add(column = new TreeListColumn("进度", "进度", 100)
                {
                    Tag = new MileStoneProgressItemDelegate(),
                    CustomCellPainter = new ProgressCellPainter()
                });

            tvMileStone.ItemDelegate = new MileStoneItemDelegate(tvMileStone);
            tvMileStone.ContextMenuStrip = contextMenuStrip1;

            MileStoneManager.Instance.ReloadMileStones();

            Dictionary<string, TreeListNode> nodeMap = new Dictionary<string, TreeListNode>();
            foreach (MileStone milestone in MileStoneManager.Instance.MileStones)
            {
                MileStoneEditData editData = new MileStoneEditData(milestone);

                TreeListNode node = CreateNode(editData);

                nodeMap.Add(milestone.Code, node);

                TreeListNode parentNode = null;
                int pos = milestone.Code.LastIndexOf(")(");

                if (pos != -1)
                {
                    string parentCode = milestone.Code.Substring(0, pos + 1);
                    if (nodeMap.ContainsKey(parentCode))
                        parentNode = nodeMap[parentCode];
                }
                if (parentNode == null)
                    tvMileStone.Nodes.Add(node);
                else
                    parentNode.Nodes.Add(node);

                editDatas.Add(editData);
            }
            tvMileStone.ExpandAll();
        }

        void tvMileStone_ItemDrop(object sender, TreeListViewDropEventArgs e)
        {
            ContextMenu cm = new ContextMenu();
            MenuItem item = new MenuItem("做为子项[&S]");
            item.Click += delegate(object sender2, EventArgs e2)
            {
                foreach (TreeListNode node in e.Nodes)
                {
                    node.Owner.Remove(node);
                    e.TargetNode.Nodes.Add(node);
                }
            };
            cm.MenuItems.Add(item);
            item = new MenuItem("同级移动[&C]");
            item.Click += delegate(object sender2, EventArgs e2)
            {
                foreach (TreeListNode node in e.Nodes)
                {
                    node.Owner.Remove(node);
                    e.TargetNode.Owner.InsertAfter(node, e.TargetNode);
                }
            };
            cm.MenuItems.Add(item);

            cm.Show(tvMileStone, tvMileStone.PointToClient(e.DropPosition));

        }

        void tvMileStone_ItemDrag(object sender, TreeListViewDragEventArgs e)
        {
            e.Cancel = true;

        }

        private static TreeListNode CreateNode(MileStoneEditData editData)
        {
            string[] cells =
                {
                    editData.Code,
                    editData.Name,
                    editData.StartTime.ToLongDateString(),
                    editData.EndTime.ToLongDateString(),
                    editData.Manager,
                    editData.Progress.ToString()
                };
            TreeListNode node = new TreeListNode(cells);
            node.Tag = editData;
            editData.Node = node;
            return node;
        }
        /// <summary>
        /// 保存里程碑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnSave(object sender, EventArgs e)
        {
            //保存里程碑分为三个过程：
            //删除被删除了的里程碑
            //添加被添加了的里程碑
            //修改被修改了的里程碑 
            StringBuilder sb = new StringBuilder();
            foreach (MileStoneEditData data in editDatas)
            {
                switch (data.EditState)
                {
                    case MileStoneEditState.Removed:
                        SP.DeleteMileStone(data.OldCode);
                        break;
                    case MileStoneEditState.Added:
                        SP.CreateMileStone(data.Code, data.Name, data.StartTime, data.EndTime, data.Manager, data.Progress);
                        break;
                    case MileStoneEditState.Changed:
                        SP.UpdateMileStone(data.OldCode, data.Code, data.Name, data.StartTime, data.EndTime, data.Manager, data.Progress);
                        break;
                    //case MileStoneEditState.Normal:
                    //    if (!data.OldCode.Equals(data.Code))
                    //    {
                    //        SP.UpdateMileStone(data.Code, data.NewCode, data.Name, data.StartTime, data.EndTime, data.Manager, data.Progress);
                    //    }
                    //    break;
                }
            }
            //Dialogs.Information(sb.ToString(), "");
            MileStoneManager.Instance.ReloadMileStones();
            DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 在所选的节点后面添加一个节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnAddMileStone(object sender, EventArgs e)
        {
            TreeListNode refNode = tvMileStone.SelectedNode;
            MileStoneEditData refData = null;
            if (refNode != null)
                refData = (MileStoneEditData)refNode.Tag;
            string manager = "";
            if (refData != null)
                manager = refData.Manager;
            MileStoneEditData data = new MileStoneEditData 
            {
                EditState = MileStoneEditState.Added ,
                Name="新里程碑",
                StartTime=DateTime.Now,
                EndTime=DateTime.Now+new TimeSpan(30,0,0,0),
                Progress=0,
                Manager=manager
            };
            
            editDatas.Add(data);
            TreeListNode newNode = CreateNode(data);

            if (refNode != null)
                refNode.Owner.InsertAfter(newNode,refNode);
            else
                tvMileStone.Nodes.Add(newNode);

        }
 
        private void OnRemoveMileStone(object sender, EventArgs e)
        {
            if (tvMileStone.SelectedNode == null)
                return;
            MileStoneEditData data = tvMileStone.SelectedNode.Tag as MileStoneEditData;
            if (!Dialogs.Confirm(this, string.Format("是否删除里程碑“{0}”？", data.Name), "删除里程碑"))
                return;
            data.MarkRemoved();
            tvMileStone.SelectedNode.Remove();
        }



    }



    public enum MileStoneEditState
    {
        Added,
        Removed,
        Normal,
        Nothing,
        Changed
    }


    class MileStoneEditData : MileStone
    {
        public MileStoneEditState EditState { get; set; }
        public TreeListNode Node { get; set; }
        public string OldCode { get; set; }

        //public void UpdateNewCode()
        //{
        //    string newCode = "";
        //    TreeListNode node = this.Node;
        //    while (node != null)
        //    {
        //        newCode = string.Format("({0})", node.NodeIndex + 1) + newCode;
        //        node = node.Parent;
        //    }
        //    NewCode = newCode;
        //}

        public MileStoneEditData(MileStone origin)
        {
            AssignFrom(origin);
            OldCode = origin.Code;
            this.EditState = MileStoneEditState.Normal;
        }
        public MileStoneEditData()
        {
        }
        internal void MarkRemoved()
        {
            if (EditState == MileStoneEditState.Added)
            {
                EditState = MileStoneEditState.Nothing;
                return;
            }
            EditState = MileStoneEditState.Removed;
        }
        internal void MarkChanged()
        {
            if (EditState == MileStoneEditState.Normal)
                EditState = MileStoneEditState.Changed;
        }
    };
    class MileStoneItemDelegate : ItemDelegate
    {
        private TreeListView treeListView;
        public MileStoneItemDelegate(TreeListView treeListView)
        {
            this.treeListView = treeListView;
        }

        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {
            //cell.ColumnIndex            
            TreeListColumn column = treeListView.Columns[cell.ColumnIndex];
            ItemDelegate id = column.Tag as ItemDelegate;
            if (id != null)
            {
                return id.CreateEditor(treeListView, cell);
            }
            return base.CreateEditor(treeListView, cell);
        }
        public override void SetCellData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            TreeListColumn column = treeListView.Columns[cell.ColumnIndex];
            ItemDelegate id = column.Tag as ItemDelegate;
            if (id != null)
            {
                id.SetCellData(treeListView, editor, cell);
            }
            else
                base.SetCellData(treeListView, editor, cell);
        }
        public override void SetEditorData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            TreeListColumn column = treeListView.Columns[cell.ColumnIndex];
            ItemDelegate id = column.Tag as ItemDelegate;
            if (id != null)
            {
                id.SetEditorData(treeListView, editor, cell);
            }
            else
                base.SetEditorData(treeListView, editor, cell);
        }
        public override void UpdateEditorGeometry(TreeListView treeListView, Control editor, NodeCell cell)
        {
            TreeListColumn column = treeListView.Columns[cell.ColumnIndex];
            ItemDelegate id = column.Tag as ItemDelegate;
            if (id != null)
            {
                id.UpdateEditorGeometry(treeListView, editor, cell);
            }
            else
                base.UpdateEditorGeometry(treeListView, editor, cell);
        }
    }
    class MileStoneCodeItemDelegate : ItemDelegate
    {
        Regex codePattern;
        public MileStoneCodeItemDelegate()
        {
            codePattern = new Regex(@"^(\(\d+\))+$", RegexOptions.Singleline);
        }

        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {
            return new TextBox { };
        }
        public override void SetCellData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            MileStoneEditData parentData = null;
            if (cell.Node.Parent != null)
                parentData = cell.Node.Parent.Tag as MileStoneEditData;
            string newValue = editor.Text.Trim();
            if (codePattern.IsMatch(newValue))
            {
                if (parentData != null && !newValue.StartsWith(parentData.Code))
                {
                    Dialogs.Error("该编码不属于父里程碑！", "新编码");
                    return;
                }

                cell.Text = data.Code = newValue;
                data.MarkChanged();
                //按编码进行排序

                treeListView.SortColumn(treeListView.Columns[0], ColumnSort.Ascending);

            }
            else
            {
                Dialogs.Error("无效的格式！", "新编码");
            }

        }
        public override void SetEditorData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            editor.Text = data.Code;
        }
    }
    class MileStoneNameItemDelegate : ItemDelegate
    {
        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {
            return new TextBox { };
        }
        public override void SetCellData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            cell.Text = data.Name = editor.Text;
            data.MarkChanged();
            
        }
        public override void SetEditorData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            editor.Text = data.Name;
        }
    }
    class MileStoneStartTimeItemDelegate : ItemDelegate
    {
        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            DatePicker picker = new DatePicker();
            picker.Date = data.StartTime;
            picker.DatePicked = delegate(DateTime? dateTime)
            {
                if (dateTime.HasValue)
                {
                    data.StartTime = dateTime.Value;
                    cell.Text = dateTime.Value.ToLongDateString();
                    data.MarkChanged();
                }
            };
            picker.Show();
            return base.CreateEditor(treeListView, cell);
        }
    }
    class MileStoneEndTimeItemDelegate : ItemDelegate
    {
        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            DatePicker picker = new DatePicker();
            picker.Date = data.EndTime;
            picker.DatePicked = delegate(DateTime? dateTime)
            {
                if (dateTime.HasValue)
                {
                    data.EndTime = dateTime.Value;
                    cell.Text = dateTime.Value.ToLongDateString();
                    data.MarkChanged();
                }
            };
            picker.Show();
            return base.CreateEditor(treeListView, cell);
        }
    }
    class MileStoneManagerItemDelegate : ItemDelegate
    {
        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {

            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);

            ChooseUser chooseUser = new ChooseUser();
            chooseUser.SelectedUsers = new string[] { data.Manager };
            chooseUser.MultiSelect = false;
            chooseUser.UserSelected +=
                delegate(object sender, EventArgs e)
                {
                    if (chooseUser.SelectedUsers.Length != 0)
                    {
                        data.Manager = chooseUser.SelectedUsers[0];
                        cell.Text = data.Manager;
                        data.MarkChanged();
                    }
                };
            chooseUser.LoadUsers();
            chooseUser.Show();
            

 



            return base.CreateEditor(treeListView, cell);
        }
    }
    class MileStoneProgressItemDelegate : ItemDelegate
    {
        public override Control CreateEditor(TreeListView treeListView, NodeCell cell)
        {
            NumericUpDown ret = new NumericUpDown();
            ret.Minimum = 0;
            ret.Maximum = 100;
            ret.Increment = 1;
            ret.TextAlign = HorizontalAlignment.Center;
            
            
            return ret;
        }
        public override void SetCellData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            data.Progress = (int)(editor as NumericUpDown).Value;
            data.MarkChanged();
        }
        public override void SetEditorData(TreeListView treeListView, Control editor, NodeCell cell)
        {
            MileStoneEditData data = (cell.Node.Tag as MileStoneEditData);
            (editor as NumericUpDown).Value = data.Progress;
        }

    }
    
}
